package com.tianhui.consignortwofei.mvp.ui.activity.audit.vehicle;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonResponse;
import com.fgs.common.entity.CommonDataListInfo;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.CheckUtil;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseDataListActivity;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.mvp.contract.DriverContract;
import com.tianhui.consignortwofei.mvp.model.DriverModel;
import com.tianhui.consignortwofei.mvp.model.VehicleModel;
import com.tianhui.consignortwofei.mvp.model.enty.DriverInfo;
import com.tianhui.consignortwofei.mvp.model.enty.VehicleInfo;
import com.tianhui.consignortwofei.mvp.presenter.DriverPresenter;
import com.tianhui.consignortwofei.mvp.ui.adapter.DriverBindAdapter;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2021/3/29
 * @description
 **/
public class BindDriverActivity extends BaseDataListActivity<DriverContract.View, DriverContract.Presenter> implements DriverContract.View {
    @BindView(R.id.layout_search_editText)
    EditText mSearchEditText;

    private DriverModel mDriverModel;
    private VehicleModel mVehicleModel;
    private VehicleInfo mVehicleInfo;
    private String mSearchKey;
    private DriverBindAdapter mAdapter;
    private boolean isNeedRequestDriverList;
    private List<DriverInfo> mDriverInfoList = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_bind_driver;
    }

    @Override
    public DriverContract.Presenter createPresenter() {
        return new DriverPresenter(this);
    }

    @Override
    public DriverContract.View createView() {
        return this;
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        mAdapter = new DriverBindAdapter(this);
        return mAdapter;
    }

    @Override
    protected void initListener() {

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                DriverInfo driverInfo = null;
                Object object = mAdapter.getAllData().get(position);
                if (object instanceof DriverInfo) {
                    driverInfo = (DriverInfo) object;
                }
                if (driverInfo == null) return;
                switch (view.getId()) {
                    case R.id.item_driver_bind_driverBindButton:
                        showDriverBindDialog(driverInfo);
                        break;
                    case R.id.item_driver_bind_driverUnbindButton:
                        showDriverUnbindDialog(driverInfo);
                        break;
                    case R.id.item_driver_bind_defaultDriverButton:
                        showDefaultDriverDialog(driverInfo);
                        break;
                }
            }
        });
    }

    private void showDriverBindDialog(DriverInfo driverInfo) {
        new MaterialDialog.Builder(this)
                .content("确认要绑定司机吗？")
                .positiveText("是")
                .negativeText("否")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        requestDriverBind(driverInfo);
                    }
                })
                .show();
    }

    private void showDriverUnbindDialog(DriverInfo driverInfo) {
        new MaterialDialog.Builder(this)
                .content("确认要解绑司机吗？")
                .positiveText("是")
                .negativeText("否")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        requestDriverUnbind(driverInfo);
                    }
                })
                .show();
    }

    private void showDefaultDriverDialog(DriverInfo driverInfo) {
        new MaterialDialog.Builder(this)
                .content("确认要设为默认司机吗？")
                .positiveText("是")
                .negativeText("否")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        requestDefaultDriver(driverInfo);
                    }
                })
                .show();
    }

    private void requestDriverBind(DriverInfo driverInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("id", mVehicleInfo.id);
        map.put("driverno", driverInfo.driverno);
        mDriverModel.driverBindModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    requestVehicleInfo(mVehicleInfo);
                    EventBusManage.refreshVehicleList();
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void requestDriverUnbind(DriverInfo driverInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("id", mVehicleInfo.id);
        map.put("driverno", driverInfo.driverno);
        mDriverModel.driverUnbindModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    requestVehicleInfo(mVehicleInfo);
                    EventBusManage.refreshVehicleList();
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void requestDefaultDriver(DriverInfo driverInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("vehiclenum", mVehicleInfo.vehiclenum);
        map.put("driverno", driverInfo.driverno);
        mDriverModel.defaultDriverModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    requestVehicleInfo(mVehicleInfo);
                    EventBusManage.refreshVehicleList();
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        if (mVehicleInfo == null) {
            showToast("获取车辆信息失败");
            return;
        }
        if (!isNeedRequestDriverList) {
            if (getIsRefresh()) {
                requestVehicleInfo(mVehicleInfo);
            }
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("limit", "10");
        map.put("order", "desc");
        map.put("page", page + "");
        map.put("sort", "create_time");
        map.put("id", mVehicleInfo.id);
        map.put("driverid", mVehicleInfo.driverid);
        if (!TextUtils.isEmpty(mSearchKey)) {
            if (CheckUtil.isContainsNum(mSearchKey)) {
                map.put("drivertel", mSearchKey);
            } else {
                map.put("drivername", mSearchKey);
            }
        }
        mDriverModel.driverListModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<CommonDataListInfo<DriverInfo>>>() {
            @Override
            public void onNext(CommonResponse<CommonDataListInfo<DriverInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {

                    CommonDataListInfo<DriverInfo> commonDataListInfo = commonResponse.getData();
                    if (commonDataListInfo != null) {
                        setPageInfo(commonDataListInfo.current, commonDataListInfo.pages);
                        List<DriverInfo> list = commonDataListInfo.records;
                        if (list != null && list.size() > 0) {
                            showDataList(list);
                        } else {
                            showEmptyView();
                        }
                    }

                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });

    }

    @Override
    public void initData() {
        setTitle("司机绑定");
        mDriverModel = new DriverModel();
        mVehicleModel = new VehicleModel();
        mSearchEditText.setHint("请输入司机姓名或司机手机号");
        Bundle bundle = getIntent().getExtras();
        if (bundle != null && !bundle.isEmpty()) {
            mVehicleInfo = bundle.getParcelable(KeyValue.KEY_VEHICLE_INFO);
            mSearchKey = bundle.getString(KeyValue.KEY_SEARCH);
            if (mVehicleInfo != null) {
                requestVehicleInfo(mVehicleInfo);
            }
        }

        //请求车辆信息，得到driverId
        //1.若driverId为空则请求司机列表
        //绑定司机后，刷新：请求车辆信息，清空所有司机列表信息
        //2.若driverId不为空，请求司机信息，并全部显示，此时不需要请求司机列表
        //解绑司机后，刷新：请求车辆信息，清空所有司机列表信息
    }

    private void needRequestDriverList() {
        isNeedRequestDriverList = true;
        refreshData(true);
    }

    private void clearInfo() {
        mDriverInfoList.clear();
        mAdapter.clear();
        isNeedRequestDriverList = false;
        mAdapter.setDriverId("");
    }

    private void requestVehicleInfo(VehicleInfo vehicleInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("id", vehicleInfo.id);
        mVehicleModel.vehicleInfoModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<VehicleInfo>>() {
            @Override
            public void onNext(CommonResponse<VehicleInfo> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        mVehicleInfo = commonResponse.getData();
                        if (mVehicleInfo != null) {
                            clearInfo();
                            if (!TextUtils.isEmpty(mVehicleInfo.driverid)) {
                                mAdapter.setDriverId(mVehicleInfo.driverid);
                                String[] ids = mVehicleInfo.driverid.split(",");
                                ArrayList<String> list = new ArrayList<>();
                                for (int i = 0; i < ids.length; i++) {
                                    list.add(ids[i]);
                                }
                                if (list != null && list.size() > 0) {
                                    requestDriverInfo(list);
                                }
                            } else {
                                needRequestDriverList();
                            }
                        }
                    }
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void requestDriverInfo(ArrayList<String> list) {
        Map<String, String> map = new HashMap<>();
        map.put("id", list.get(0));
        mDriverModel.driverInfoModel(this, map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<DriverInfo>>() {
            @Override
            public void onNext(CommonResponse<DriverInfo> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        DriverInfo driverInfo = commonResponse.getData();
                        if (driverInfo != null) {
                            setPageInfo(1, 1);
                            mDriverInfoList.add(driverInfo);
                        }
                        if (list.size() > 1) {
                            list.remove(0);
                            requestDriverInfo(list);
                            return;
                        }
                        if (mDriverInfoList.size() > 0) {
                            showDataList(mDriverInfoList);
                        } else {
                            needRequestDriverList();
                        }
//                        }
                    } else {
                        needRequestDriverList();
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                needRequestDriverList();
            }
        });
    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    @OnClick(R.id.layout_search_textView)
    public void search() {
        mSearchKey = mSearchEditText.getText().toString().trim();
        if (!TextUtils.isEmpty(mSearchKey)) {
            needRequestDriverList();
        } else {
            requestVehicleInfo(mVehicleInfo);
        }
    }


}
